<?php
namespace cms\modules\v1\models\redPacket;

use cms\modules\v1\models\user\User;
use common\models\Functions;
use yii\base\Exception;
use Yii;
use yii\helpers\ArrayHelper;

/**
 * This is the model class for table "goods".
 *
 * @property int $id
 * @property string $name
 */
class RedPacket extends \common\models\redPacket\RedPacket
{

    /**
     * 返回列表数据
     * @param int $page
     * @param int $size
     * @return array
     */
    public function getListData($page = 1, $size = 20) {
        try {
            //搜索条件
            $searchWhere  = $this->getSearch();//自定义搜索条件
            //得到文章的总数
            $count = static::getObjectCountByAndWhere($searchWhere['where'], $searchWhere['andWhere'])->count();
            $data = static::setPageinationAPI($page, $size, $count);
            //设置分页
            $offset = ($page - 1) * $size;

            //排序 order
            $orderSql = 'id DESC';

            $query = static::getObjectByAndWhere($searchWhere['where'],$searchWhere['andWhere'], '*', $orderSql, $offset, $size);
            $data['data'] = $this->handelList($query);

            return Functions::formatRestAPI(0, '', $data);
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 自定义参数的搜索  搜索,搜索也分每一列
     * 这里要根据业务逻辑进行修改
     */
    public function getSearch () {
        $where = [];
        $andWhere = [];
        $phone = Yii::$app->request->get('phone','');
        $type = Yii::$app->request->get('type','');
        $status = Yii::$app->request->get('status','');
        $startTime = Yii::$app->request->get('start','');
        $endTime = Yii::$app->request->get('end','');

        if($status){
            $where['status'] = $status;
        }
        if($type){
            $where['type'] = $type;
        }
        if ($phone) {
            $andWhere[] = ['like', "user_phone", $phone];
        }

        if(!empty($startTime) && empty($endTime)) {
            $andWhere[] = ['>','create_time',$startTime];
        } elseif(empty($startTime) && !empty($endTime)) {
            $andWhere[] = ['<','create_time',$endTime];
        } elseif (!empty($startTime) && !empty($endTime)) {
            $andWhere[] = ['between','create_time',$startTime, $endTime];
        }
        return [
            'where' => $where,
            'andWhere' => $andWhere,
        ];
    }

    /**
     * 处理初始化数据
     * @param $query
     * @return mixed
     */
    public function handelList($query = null) {
        if (empty($query)) {
            return null;
        }

        $list = $query->with([

        ])->asArray()->all();

//        foreach ($list as &$v) {
//            $v['time'] = $v['update_time'] ?: $v['create_time'];
//            $v['yx_num'] = floatval($v['yx_num']) ?: 0;
//            $v['image'] = static::getImages($v['image']);
//        }
        return $list;
    }


}
